package tools.httptools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;

public class TelnetUtils {
    public static boolean telnet(String hostname, int port, int timeout){
        Socket socket = new Socket();
        boolean isConnected = false;
        try {
            socket.connect(new InetSocketAddress(hostname, port), timeout); // 建立连接
            isConnected = socket.isConnected(); // 通过现有方法查看连通状态
//            System.out.println(isConnected);    // true为连通
        } catch (IOException e) {
            System.out.println("false");        // 当连不通时，直接抛异常，异常捕获即可
        }finally{
            try {
                socket.close();   // 关闭连接
            } catch (IOException e) {
                System.out.println("false");
            }
        }
        return isConnected;
    }

    // 判断网络状态
    public String isConnect() throws Exception {
        BufferedReader br = null;
        try{
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec("ping " + "www.baidu.com");
            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "GB2312");
            br = new BufferedReader(inputStreamReader);
            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            if(!sb.toString().contains("平均")){
                return "无网络";
            }
            else{
                return sb.toString().substring(sb.toString().lastIndexOf("平均")+5,sb.length());
            }
        }catch (Exception e){
            throw new Exception();
        }finally {
            if (br != null){
                br.close();
            }
        }
    }


//    public static void main(String[] args) {
////        String hostname = "14.215.178.37";
//        String hostname = "172.19.0.99";    // hostname 可以是主机的 IP 或者 域名
//        int port = 80;
//        int timeout = 200;
//        boolean isConnected = telnet(hostname, port, timeout);
//        System.out.println("telnet "+ hostname + " " + port + "\n==>isConnected: " + isConnected);
//    }

    public static void main(String[] args) {
        boolean telnet = telnet("10.144.108.98", 8080, 200);
        System.out.println(telnet);
    }

}
